package com.nest.WorkNest.act;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.lidroid.xutils.exception.HttpException;
import com.llf.util.Alipay;
import com.llf.util.Constants;
import com.llf.util.PayResult;
import com.nest.WorkNest.MyApplication;
import com.nest.WorkNest.R;
import com.nest.WorkNest.api.XutilsPost;
import com.nest.WorkNest.entity.PaymentInfo;
import com.nest.WorkNest.tools.ParseUtils;
import com.nest.WorkNest.tools.PhoneHelper;
import com.nest.WorkNest.tools.Tool;
import com.orhanobut.logger.Logger;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by chenchuan on 2015/8/27 0027.
 */
public class PaymentAct extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.tv_payment_integral)
    TextView tvPaymentIntegral;
    @Bind(R.id.ll_payment_alipay)
    LinearLayout llPaymentAlipay;
    @Bind(R.id.ll_payment_wechat)
    LinearLayout llPaymentWechat;
    @Bind(R.id.tv_payment_beforeprice)
    TextView tvPaymentBeforeprice;
    @Bind(R.id.chk_payment_useintegral)
    CheckBox chkPaymentUseintegral;
    @Bind(R.id.tv_payment_afterprice)
    TextView tvPaymentAfterprice;
    @Bind(R.id.ll_payment_integralpay)
    LinearLayout llPaymentIntegralpay;
    @Bind(R.id.tv_payment_content)
    TextView tvPaymentContent;
    @Bind(R.id.tv_payment_totalprice)
    TextView tvPaymentTotalprice;
    @Bind(R.id.edtTxt_payment_integral)
    EditText edtTxtPaymentIntegral;
    private Context context = PaymentAct.this;
    private float integral, useIntegral;
    private float beforeprice, afterprice;
    private String toPayId;
    private PaymentInfo paymentInfo;
    private Intent mIntent;
    private HashMap<String, String> pay = new HashMap<>();
    private ArrayList<HashMap<String, String>> paylist = new ArrayList<>();
    protected MyApplication myApp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_payment);
        ButterKnife.bind(this);
        initView();
        loadTopayDetail();
    }

    public void initView() {
        initBar();
        myApp = (MyApplication) getApplication();
        myApp.tabHostId = 0;
        actionbar_side_name.setVisibility(View.VISIBLE);
        actionbar_side_name.setText("订单支付");
        ll_iv_actionbar_side_left.setVisibility(View.VISIBLE);
        mIntent = getIntent();
//        beforeprice = getIntent().getFloatExtra("totalprice", 0);
        if (mIntent.getStringExtra("toPayId") != null) {
            toPayId = mIntent.getStringExtra("toPayId");
        } else {
            showToast("获取信息失败");
            finish();
        }
        llPaymentIntegralpay.setOnClickListener(this);
        llPaymentAlipay.setOnClickListener(this);
        back();
        edtTxtPaymentIntegral.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                int len = s.toString().length();
                if ((len > 1 && text.substring(0, 1).equals("0")) && !(len > 1 && text.substring(1, 2).equals("."))) {
                    edtTxtPaymentIntegral.setText(text.substring(1));
                } else if (TextUtils.isEmpty(text)) {
                    edtTxtPaymentIntegral.setText("0");
                } else if (ParseUtils.string2float(text) > beforeprice) {
                    edtTxtPaymentIntegral.setText(beforeprice + "");
                } else {
                    useIntegral = ParseUtils.string2float(text);
                    BigDecimal b1 = new BigDecimal(Float.toString(beforeprice));
                    BigDecimal b2 = new BigDecimal(Float.toString(useIntegral));
                    afterprice = b1.subtract(b2).floatValue();
                    if (afterprice <= 0f) {
                        llPaymentIntegralpay.setVisibility(View.VISIBLE);
                        tvPaymentAfterprice.setText("0");
//                        if (afterprice == 0) {
                        paymentInfo.setPaySum1(beforeprice);
                        paymentInfo.setPaySum(0f);
//                        } else if (afterprice < 0) {
//                        paymentInfo.setPaySum(integral);
//                        }
                    } else {
                        llPaymentIntegralpay.setVisibility(View.GONE);
                        tvPaymentAfterprice.setText(afterprice + "");
                        paymentInfo.setPaySum(afterprice);
                        paymentInfo.setPaySum1(useIntegral);
//                        paymentInfo.setPaySum(afterprice);
                    }
                }
                edtTxtPaymentIntegral.setSelection(edtTxtPaymentIntegral.getText().length());
            }
        });
        chkPaymentUseintegral.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if ("".equals(edtTxtPaymentIntegral.getText().toString())) {
                    edtTxtPaymentIntegral.setText("0");
                }
                if (isChecked) {
                    edtTxtPaymentIntegral.setFocusable(true);
                    edtTxtPaymentIntegral.setFocusableInTouchMode(true);
                    edtTxtPaymentIntegral.requestFocus();
                    edtTxtPaymentIntegral.requestFocusFromTouch();
                    edtTxtPaymentIntegral.setSelection(0);
                    if (beforeprice > integral) {
                        edtTxtPaymentIntegral.setText(integral + "");
                    } else {
                        edtTxtPaymentIntegral.setText(beforeprice + "");
                    }
                } else {
                    edtTxtPaymentIntegral.setFocusable(false);
                    edtTxtPaymentIntegral.setFocusableInTouchMode(false);
                    tvPaymentAfterprice.setText(beforeprice + "");
                    paymentInfo.setPaySum(beforeprice);
                    llPaymentIntegralpay.setVisibility(View.GONE);
                }
            }
        });

    }

    public void loadPaywithoutCrash(PaymentInfo paymentInfo) {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                Logger.json(result);
                if (Tool.getString(result, "resultCode").equals("0")) {
                    showToast("支付成功");
                    startActivity(new Intent(PaymentAct.this, MainTabAct.class));
                    finish();
                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                } else {
                    startActivity(new Intent(PaymentAct.this, MainTabAct.class));
                    showToast("支付失败,请到待支付列表或者联系客服");
                    finish();
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostPay(context, paymentInfo, ioAuthCallBack);
    }


    public void loadUserDetail() {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                if (Tool.getString(result, "resultCode").equals("0")) {
                    String userInfo = Tool.getString(result, "user");
                    integral = ParseUtils.string2float(Tool.getString(userInfo, "integral"));
                    if (!TextUtils.isEmpty(integral + "")) {
                        tvPaymentIntegral.setText(integral + ")");
                        if (beforeprice > integral) {
                            edtTxtPaymentIntegral.setText(integral + "");
                        } else {
                            edtTxtPaymentIntegral.setText(beforeprice + "");
                        }
                    }
                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostUserDetail(context, ioAuthCallBack);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_payment_integralpay:
                loadPaywithoutCrash(paymentInfo);
                break;
            case R.id.ll_payment_alipay:
                if (chkPaymentUseintegral.isChecked()) {
                    paymentInfo.setPaySum(afterprice);
                    paymentInfo.setPaySum1(useIntegral);
                    alipay(paymentInfo.getPaySum());
//                    loadPaywithoutCrash(paymentInfo);

                } else {
                    paymentInfo.setPaySum(beforeprice);
                    paymentInfo.setPaySum1(0f);
//                    loadPaywithoutCrash(paymentInfo);
                    alipay(beforeprice);
                }
                break;
        }
    }

    public void loadTopayDetail() {
        XutilsPost xutilsPost = new XutilsPost();
        XutilsPost.IOAuthCallBack ioAuthCallBack = new XutilsPost.IOAuthCallBack() {
            @Override
            public void getIOAuthCallBack(String result) {
                Logger.d(result);
                if (Tool.getString(result, "resultCode").equals("0")) {
                    try {
                        String dataList = Tool.getString(result, "dataList");
                        paylist = Tool.getListMapByJsonArrayString(dataList);
                        if (paylist.get(0) != null) {
                            pay = paylist.get(0);
                            beforeprice = ParseUtils.string2float(pay.get("remain"));
                            tvPaymentBeforeprice.setText(beforeprice + "");
                            tvPaymentAfterprice.setText(beforeprice + "");
                            tvPaymentContent.setText(pay.get("payContent"));
                            tvPaymentTotalprice.setText(ParseUtils.string2float(pay.get("totalAmount")) + "");
                            paymentInfo = new PaymentInfo();
                            paymentInfo.setOrderId(pay.get("orderId"));
                            paymentInfo.setPaySum(beforeprice);
//        paymentInfo.setPaySum(0.01f);
                            paymentInfo.setPaySerialNumber(pay.get("orderId"));
                            paymentInfo.setToPayId(pay.get("toPayId"));
                            paymentInfo.setPayUserName(pay.get("payUserName"));
                            paymentInfo.setPayTime(PhoneHelper.getCurrentTime());
                            paymentInfo.setCollectionAccount(Constants.SELLER);
                            paymentInfo.setCollectionUserName("gckj");
                            paymentInfo.setPayContent(pay.get("payContent"));
                            paymentInfo.setRemark(pay.get("remark"));
                            paymentInfo.setPayAccount(pay.get("payAccount"));
                            loadUserDetail();
                        } else {
                            finish();
                        }
                    } catch (Exception e) {
                        showToast("待支付订单不存在");
                        finish();
                    }

                } else if (Tool.getString(result, "resultCode").equals("9001")) {
                    showToast("token已过期，请重新登录");
                    Intent intent = new Intent(context, LoginAct.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void getDealException(HttpException httpException, String result) {

            }

            @Override
            public void getLoadingCallBack(long total, long current, boolean isUploading) {

            }
        };
        xutilsPost.doPostqueryToPayRecords(context, toPayId, ioAuthCallBack);
    }

    public void alipay(float price) {
        final String orderInfo = Alipay.getOrderInfo(paymentInfo.getOrderId(), paymentInfo.getPayContent(), price + "");
        AsyncTask<String, Void, String> task = new AsyncTask<String, Void, String>() {

            @Override
            protected String doInBackground(String... params) {
                String payInfo = Alipay.pay(orderInfo);
                // 构造PayTask对象
                PayTask alipay = new PayTask(PaymentAct.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo);
                return result;
            }

            @Override
            protected void onPostExecute(String result) {
                PayResult payResult = new PayResult(result);
                String resultStatus = payResult.getResultStatus();
                if (TextUtils.equals(resultStatus, "9000")) {
                    loadPaywithoutCrash(paymentInfo);
                } else {
                    if (TextUtils.equals(resultStatus, "8000")) {
                        showToast("支付结果确认中");
                    } else {
                        startActivity(new Intent(PaymentAct.this, MainTabAct.class));
                        showToast("支付失败,请到待支付列表或者联系客服");
                        finish();
                    }
                }
            }
        };
        task.execute();
    }
}
